<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-button type="primary" @click="adddialogVisible = true">添加角色</el-button>
      <el-table border :data="RolesList" stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row v-for="(item1, i1) in scope.row.children" :key="item1.id"
              :class="['border_bottom', i1 === 0 ? 'border_top' : '', 'vcenter']">
              <el-col :span="5">
                <el-tag @close="removeRights(scope.row, item1.id)" closable>{{ item1.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row v-for="(item2, i2) in item1.children" :key="item2.id"
                  :class="[i2 === 0 ? '' : 'border_top', 'vcenter']">
                  <el-col :span="7">
                    <el-tag type="success" @close="removeRights(scope.row, item2.id)" closable>{{ item2.authName
                    }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="12">
                    <el-tag type="warning" v-for="(item3, i3) in item2.children" :key="item3.id" closable
                      :class="[i3 === 0 ? '' : 'border_top']" @close="removeRights(scope.row, item3.id)">
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="290px">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini"
              @click="editdialogVisibles(scope.row.id)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="editDetel(scope.row.id)">删除</el-button>
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="setroles(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加对话框 -->
    <el-dialog title="添加" :visible.sync="adddialogVisible" width="50%" @close="addclose">
      <el-form :model="addruleForm" :rules="addrules" ref="addruleFormref" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addruleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addruleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="adddialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑对话框 -->
    <el-dialog title="编辑" :visible.sync="editdialogVisible" width="50%">
      <el-form :model="editruleForm" :rules="editrules" ref="editruleFormRef" label-width="80px">
        <el-form-item label="id">
          <el-input v-model="editruleForm.roleId" disabled=""></el-input>
        </el-form-item>
        <el-form-item label="角色名称">
          <el-input v-model="editruleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="editruleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog title="提示" :visible.sync="setRolesdialogVisible" width="30%" @close="rightclose">
      <el-tree ref="treeRef" :data="setRolesList" :props="treeProp" show-checkbox default-expand-all node-key="id"
        :default-checked-keys="arrid"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRolesdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Roles',
  created () {
    this.getRolesList()
  },
  data () {
    return {
      RolesList: [],
      editdialogVisible: false,
      adddialogVisible: false,
      editruleForm: {
      },
      editrules: {

      },
      addruleForm: {
        roleName: '',
        roleDesc: ''
      },
      addrules: {
        roleName: [
          {
            required: true, message: '请输入', trigger: 'blur'
          },
          {
            min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur'
          }
        ],

        roleDesc: [
          {
            required: true, message: '请输入', trigger: 'blur'
          },
          {
            min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur'
          }
        ]
      },
      setRolesdialogVisible: false,
      setRolesList: [],
      treeProp: {
        label: 'authName',
        children: 'children'
      },
      arrid: [],
      roleId: 0
    }
  },
  methods: {
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('请求错误')
      this.RolesList = res.data
    },
    addclose () {
      this.$refs.addruleFormref.resetFields()
    },
    addUser () {
      this.$refs.addruleFormref.validate(async valid => {
        if (!valid) return this.$message.error('提交失败')
        const { data: res } = await this.$http.post('roles', this.addruleForm)
        if (res.meta.status !== 201) return this.$message.error('请求失败')
        this.$message.success('添加成功')
        this.getRolesList()
      })
    },
    async editdialogVisibles (id) {
      this.editdialogVisible = true
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) return this.$message.error('请求错误')
      this.editruleForm = res.data
    },
    editUser () {
      this.$refs.editruleFormRef.validate(async valid => {
        if (!valid) return this.$message.error('修改失败')
        const { data: res } = await this.$http.put('roles/' + this.editruleForm.roleId, this.editruleForm)
        if (res.meta.status !== 200) return this.$message.error('修改失败')
        this.$message.success('修改成功')
        this.getRolesList()
      })
    },
    async editDetel (id) {
      const editconfirm = await this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (editconfirm === 'confirm') {
        const { data: res } = await this.$http.delete('roles/' + id)
        if (res.meta.status !== 200) return this.$message.error('删除失败')
        this.$message.success('删除成功')
        this.getRolesList()
      }
    },
    async removeRights (role, rightId) {
      const removeconfirm = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (removeconfirm !== 'confirm') return this.$message.info('取消删除')
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      role.children = res.data
    },
    async setroles (role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('请求数据失败')
      this.setRolesList = res.data
      this.getLeafKeys(role, this.arrid)
      this.setRolesdialogVisible = true
    },
    // 递归选出每个三级权限的id
    getLeafKeys (node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    rightclose () {
      this.arrid = []
    },
    async allotRights () {
      const allidarr = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()].join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: allidarr })
      if (res.meta.status !== 200) return this.$message.error('修改失败')
      this.getRolesList()
      this.setRolesdialogVisible = false
      this.$message.success('修改成功')
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 9px;
}

.border_bottom {
  border-bottom: 1px solid #eee;
}

.border_top {
  border-top: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
  text-align: center;
}
</style>
